/**
 * Copyright (c) 2024 - CARThunder
 * All Rights Reserved by Chengdu CARThunder Intelligent Technology Co., LTD and its affiliates.
 * You may not use, copy, distribute, modify, transmit in any form this file
 * except in compliance with CARThunder in writing by applicable law.
 * <p>
 * <p>
 * file description.
 *
 * @file filename
 * @brief brief function description.
 * @details detailed function description.
 * @version 1.0
 * @author author_name
 * @date last_modified_date
 * <p>
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2024-08-2               jia fengyi         Create it.
 * <p>
 * file description.
 * @file filename
 * @brief brief function description.
 * @details detailed function description.
 * @version 1.0
 * @author author_name
 * @date last_modified_date
 * <p>
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2024-08-2               jia fengyi         Create it.
 */

/**
 * file description.
 * @file filename
 * @brief brief function description.
 * @details detailed function description.
 * @version 1.0
 * @author author_name
 * @date last_modified_date
 *
 *      Edit History
 *      ----------------------------------------------------------------------------
 *      DATE                     NAME               DESCRIPTION
 *      2024-08-2               jia fengyi         Create it.
 *
 */

package com.cart.musicdemo.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cart.musicdemo.MainActivity;
import com.cart.musicdemo.R;
import com.cart.musicdemo.adapter.FileAdapter;
import com.cart.musicdemo.base.service.FileSystemManager;
import com.cart.musicdemo.base.service.MusicService;
import com.cart.musicdemo.model.FileTreeModel;
import com.cart.musicdemo.model.SongModel;
import com.cart.musicdemo.model.UpdateEventUI;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


public class FileFragment extends Fragment {

    private FileSystemManager.FolderNode rootNode;

    private MusicService.MusicBinder musicService;

    private ImageView backImage;

    private FileAdapter fileAdapter;

    private FileFragment fragment;

    private static FileFragment fileFragment;

    //存放当前node节点所有数据，放入适配器当中
    List<Object> list;

    private View view;


    public FileFragment() {
        // Required empty public constructor
    }

    public FileFragment(FileSystemManager.FolderNode rootNode,
                        MusicService.MusicBinder musicService) {
        this.rootNode = rootNode;
        this.musicService = musicService;
        fragment = new FileFragment();
        Bundle args = new Bundle();
        //bundle无法放入Map,将其放入实体中存入
        FileTreeModel fileTreeModel = new FileTreeModel();
        fileTreeModel.setRootNode(rootNode);
        args.putParcelable("fileTree", fileTreeModel);
        args.putBinder("musicService", musicService);
        fragment.setArguments(args);
    }


    public static FileFragment newInstance(FileSystemManager.FolderNode rootNode,
                                           MusicService.MusicBinder musicService) {
        fileFragment = new FileFragment();
        Bundle args = new Bundle();
        //bundle无法放入Map,将其放入实体中存入
        FileTreeModel fileTreeModel = new FileTreeModel();
        fileTreeModel.setRootNode(rootNode);
        args.putParcelable("fileTree", fileTreeModel);
        args.putBinder("musicService", musicService);
        fileFragment.setArguments(args);
        return fileFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        if (getArguments() != null) {
            //视图创造时获取bundle传入数据
            FileTreeModel fileTreeModel = getArguments().getParcelable("fileTree");
            if (fileTreeModel.getRootNode() != null) {
                rootNode = fileTreeModel.getRootNode();
            }
            Log.d("nodeMap", "onCreate: " + rootNode);
            musicService = (MusicService.MusicBinder)
                    getArguments().getBinder("musicService");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateEventUI(UpdateEventUI event) {
        String type = event.getType();
        if (type.equals("clearUI")) {
            //拔出USB时清空数据
            list.clear();
        }
        // 更新 UI
        fileAdapter.notifyDataSetChanged();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_file_list, container, false);
        //设置文件列表
        list = new ArrayList<>();
        list.addAll(rootNode.getChildren());
        list.addAll(rootNode.getSongModels());
        backImage = view.findViewById(R.id.tv_file_back);
        //返回按钮监听
        backImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getFragmentManager().popBackStack();
            }
        });
        RecyclerView fileRecyclerView = view.findViewById(R.id.rv_file_RecyclerView);
        fileRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        fileAdapter = new FileAdapter(list, this::onItemClick);
        fileRecyclerView.setAdapter(fileAdapter);
        return view;
    }

    private void onItemClick(FileSystemManager.FolderNode folderNode,
                             SongModel songModel,
                             boolean reset) {
        //跳转至歌手所拥有歌曲
        //如果是文件夹则跳转下一个Fragment否则歌曲播放
        //跳转新的fragment
        if (folderNode != null) {
            FileFragment fileFragment = new FileFragment(folderNode, musicService);
            //fragment跳转
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.replace(R.id.file_fragment, fileFragment);
            transaction.addToBackStack("fileStack");
            transaction.commit();
        } else if (songModel != null) {
            //点击文件夹播放当前文件夹所有歌,不含子文件夹
            musicService.updateSongList(rootNode.getSongModels());
            //歌曲播放
            int position = musicService.getSonglist().indexOf(songModel);
            //设置当前musicService当中播放位置
            musicService.setCurrentPosition(position);
            musicService.play(position, true);
            fileAdapter.notifyDataSetChanged();
            //点击后更新Activity播放按钮UI
            MainActivity activity = (MainActivity) getActivity();
            if (activity != null) {
                activity.updateStartButtonStatus();
            }
        }


    }


}